import {
  Router
} from 'express'
const router = Router()
import config from 'config'
import util from '../../util'
import mysql from '../../libs/mysql'
import md5 from 'md5';

router.post('/createUser', async (req, res, next) => {
  let {
    name,
    password
  } = req.body;
  if (name && password) {
    let searchUser = `select * from users where name = ?`;
    let sql = `insert into users(name,password) values (?)`;
    let mysqlCon = await mysql.getConnect();
    let resultUser = await mysql.query(mysqlCon, searchUser, name);
    if(resultUser.length){
      let release = await mysql.release(mysqlCon)
      return res.send(util.resError({
        code:'name',
        msg: '此用户已存在'
      }))
    }
    let result = await mysql.query(mysqlCon, sql, [name, md5(md5(password))])
    let release = await mysql.release(mysqlCon)
    if (result.affectedRows !== 1) {
      return res.send(util.resError({
        msg: '插入失败'
      }))
    }
    req.session.user = {
      id: result.insertId,
      name: name
    }
    return res.send(util.resSuccess({
      data: {
        body: req.body,
        sql: result
      }
    }))
  }
  return res.send(util.resError({
    msg: '请输入名字和密码'
  }))

})
router.post('/login',async  (req, res, next) =>{
  let {
    name,
    password
  } = req.body;
  if (name && password) {
    let sql = `select * from users where name = ?`;
    let mysqlCon = await mysql.getConnect();
    let result = await mysql.query(mysqlCon, sql, name)
    let release = await mysql.release(mysqlCon);
    if(result.length){
      if(result[0]['password'] == md5(md5(password))){
        
        req.session.user = {
          id: result[0].id,
          name: name
        }
        
        return res.send(util.resSuccess({
          data:{
            name:result[0].name,
          }
        }))
      }else{
        return res.send(util.resError({
          code:'password',
          msg: '密码错误'
        }))
      }
    }else{
      return res.send(util.resError({
        code:'name',
        msg: '此人不存在'
      }))
    }
  }
  return res.send(util.resError({
    msg: '请输入名字和密码'
  }))
 
})
export default router;